package handlers

import (
	"github.com/gin-gonic/gin"
	"logi-manage/cache"
	"logi-manage/modle"
	"logi-manage/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名和密码不能为空",
		})
		return
	}

	var user modle.User
	err := modle.DB.Where("username=?", username).Debug().Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户名失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "累计错误达 3 次时，将触发账户临时封禁机制",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "累计错误达 3 次时，2 小时内无法发起登录请求",
			})
			return

		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return

	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
		"data": user,
	})
	return

}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	var data = modle.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	modle.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "success",
	})
	return

}

func UserRoleAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	uid, _ := strconv.Atoi(c.PostForm("uid"))

	var data = modle.UserRole{
		Uid: uid,
		Rid: rid,
	}
	modle.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "success",
	})
	return
}

func RoleNodeList(c *gin.Context) {

	rid, _ := strconv.Atoi(c.Query("rid"))

	var roleNodeList []modle.Node
	/*
		SELECT *
		FROM nodes
		LEFT JOIN role_nodes on nodes.id=role_nodes.nid
		WHERE role_nodes.rid=2
	*/

	modle.DB.
		Table("nodes").
		Joins("LEFT JOIN role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Find(&roleNodeList)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": roleNodeList,
	})
	return

}

func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))

	var userRoleList []modle.Role
	/*
		SELECT *
		FROM roles
		LEFT JOIN user_roles on roles.id=user_roles.rid
		WHERE user_roles.uid=1
	*/

	modle.DB.
		Table("roles").
		Joins("LEFT JOIN user_roles on roles.id=user_roles.rid").
		Where("user_roles.uid=?", uid).
		Find(&userRoleList)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": userRoleList,
	})
	return

}
